/* 
token处理的工具函数
1. 生成token
2. 校验token
*/

const jwt = require('jsonwebtoken')

const SECRET_KEY = 'wh220516_key'

/**
 * 生成并返回token
 * @param {*} userId 
 * @param {*} expireTime 
 */

/* function createToken(userId, expireTime='7d') {
  return jwt.sign({data: userId}, SECRET_KEY, {expiresIn: expireTime})
} */

//生成token函数
const createToken = (userId, expireTime = '7d') => jwt.sign({data: userId}, SECRET_KEY, {expiresIn: expireTime})


exports.createToken = createToken;

/**
 * 校验token
 * @param {*} token 
 * @returns promise对象,校验失败 promise失败,  校验成功, promise成功, 且value为userId
 */
  function  verifyToken(token){
    return new Promise((resolve, reject) => {
        //对token进行校验
        jwt.verify(token, SECRET_KEY, (err, decode) => {
            //校验失败,变为成功的promise
            if (err) {
                reject(new Error('token过期或非法'))
            } else {
                //校验成功.变为成功的promise
                resolve(decode.data)
            }
        })

    })
} 




exports.verifyToken = verifyToken


/* //测试定义函数是否正确代码
const token = createToken(123, 3)
console.log(token)
setTimeout(() => {
  verifyToken(token)
  .then(
    value => {
      console.log(value)
    },
    error => {
      console.log(error.message)
    }
  )
}, 2000); */